package com.base.thread;

import java.util.Queue;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import com.base.thread.handler.Handler;
import com.base.thread.msg.Packet;


public class SubThread extends Thread{
	
	private Queue<Packet> packetQueue;
	
	private Handler handler;
	
	private final Object lockObj = new Object();
	
	//对象锁
	private final Lock lock = new ReentrantLock();
	
	private boolean isLock = false;
	
	public SubThread() {
		super();
	}
	
	
	

	public SubThread(SubThread temp) {
		super();
		this.packetQueue = temp.getPacketQueue();
		this.handler = temp.getHandler();
		this.isLock = temp.isLock();
		this.setName(temp.getName());
	}




	public void init(String threadName,Queue<Packet> packetQueue,Handler handler) {
		this.setName(threadName);
		this.packetQueue = packetQueue;
		this.handler = handler;
	}

	

	@Override
	public void run() {
		
		while(true){
			
			try {
				
				Packet packet = packetQueue.poll();
				if(null == packet){
					seelp();
					continue;
				}
				
				//dosomething
//				handler.handler(packet);
				System.out.println(getName()+"||"+packet.toString()+"||"+packetQueue.size());
			} catch (Exception e) {
				// TODO: handle exception
			}
			
		}
		
	}

	private void seelp() throws InterruptedException {
		
		synchronized (lockObj) {
			
//			if(!packetQueue.isEmpty()){
//				return;
//			}
			
			if(!isLock()){
				setLock(true);
				lockObj.wait();
//				lock.lock();
			}
		}
		
	}
	
	public void weakUp() {
		
		synchronized (lockObj) {
			if(isLock()){
				setLock(false);
				lockObj.notify();
//				lock.unlock();
			}
		}
		
	}
	
	

	public boolean hasMsg() {
		return !packetQueue.isEmpty();
	}
	
	
	public boolean addMsg(Packet packet) {
		return packetQueue.offer(packet);
	}
	
	
	public int getMsgSize() {
		return packetQueue.size();
	}
	
	public boolean isEmpty() {
		
		if( packetQueue.size() > 0){
			return false;
		}
		return true;
	}

	public Queue<Packet> getPacketQueue() {
		return packetQueue;
	}

	public void setPacketQueue(Queue<Packet> packetQueue) {
		this.packetQueue = packetQueue;
	}

	public Handler getHandler() {
		return handler;
	}

	public void setHandler(Handler handler) {
		this.handler = handler;
	}

	public Object getLockObj() {
		return lockObj;
	}

	public boolean isLock() {
		return isLock;
	}

	public void setLock(boolean isLock) {
		this.isLock = isLock;
	}

	
	
	
	
	
	
	
	
}
